package io.renren.modules.minio.controller;

import io.renren.common.utils.Result;
import io.renren.modules.minio.service.MinioService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 *
 * @author 40659
 */
@Tag(name = "文件上传")
@RestController
@Slf4j
@RequestMapping("")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileController {

    private final static String FILE_URL_PREFIX = "/upload/";
    private final MinioService minioService;

    @Operation(summary = "文件上传（file格式）")
    @PostMapping("file/upload")
    @Parameter(name = "file", description = "文件", schema = @Schema(type = "string", format = "binary"), required = true)
    //@Parameter(name = "file", description = "文件流", in = ParameterIn.DEFAULT, required = true)
    public Result<Object> upload(@RequestPart MultipartFile file) {
        String url = FILE_URL_PREFIX + minioService.upload(file);
        return new Result<>().ok(url);
    }

    @Operation(summary = "文件上传（base64格式）")
    @PostMapping("file/uploadBase64")
    @Parameter(name = "base64String", description = "文件base64格式", in = ParameterIn.QUERY, required = true)
    public Result<Object> upload(@RequestParam String base64String) {
        String url = FILE_URL_PREFIX + minioService.uploadBase64(base64String);
        return new Result<>().ok(url);
    }

    @Operation(summary = "文件下载")
    @GetMapping("file/download")
    @Parameter(name = "filePath", description = "文件路径", in = ParameterIn.QUERY, required = true)
    public void download(@RequestParam String filePath, HttpServletResponse response) {
        minioService.download(filePath, response);
    }

    @Operation(summary = "图片预览")
    @GetMapping("/upload/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        String servletPath = request.getServletPath();
        servletPath = servletPath.replaceAll(FILE_URL_PREFIX, "");
        minioService.view(servletPath, response);
    }
}
